/**
 * 解析请求中的`X-Sid`，放到`cookie`中去
 * 解析响应中的`Set-Cookie`，放到`X-Set-Sid`中去
 */
module.exports = function (cookieName='connect.sid') {
  return function (req, res, next) {
    let sid = req.headers['x-sid']
    if (sid) {
      req.headers.cookie = (req.headers.cookie || '') + ';' + cookieName + '=' + sid
    }
    const onHeaders = require('on-headers')
    onHeaders(res, function () {
      const cookies = this.getHeader('set-cookie')
      if (cookies) {
        const cookie = cookies.filter(cookie => cookie.indexOf(cookieName) == 0)[0]
        if (cookie) {
          this.setHeader('X-Set-Sid', cookie.split(';')[0].split('=')[1])  
        }  
      }
    })
    next()
  }
}